<template>
  <h3>watchEffect</h3>
  <p>{{ name }} {{ age }}</p>
  <p>xusuiRef {{ xusuiRef }}</p>

  <p>scoreRef {{ scoreRef }}</p>
  <p>wife {{ wife }}</p>
  <button @click="stopHandler">停止侦听老娘</button>
</template>

<script>
import { ref, reactive, computed, toRefs, watch, watchEffect } from "vue";

export default {
  name: "WatchEffect",

  setup() {
    const scoreRef = ref(60);

    const state = reactive({
      name: "张三",
      age: 20,
      wife: {
        money: 123,
        friends: ["老王", "西门大官人"],
      },
    });

    const xusuiRef = computed(() => state.age + 1);
    setInterval(() => {
      state.age++;
      scoreRef.value++;
      state.wife.money++;
    }, 1000);

    /* 
    watchEffect 会自动收集依赖的侦听 
    代码在编译阶段 就会收集所有的一手数据项依赖 并全部侦听起来
    有任何一个依赖项发生变化时 就会回调副作用函数
    */
    const stopper = watchEffect(
      // 依赖发生变化时的副作用函数effect function
      () => {
        console.log("scoreRef.value", scoreRef.value);
        console.log("state.age", state.age);
        console.log("state.wife.money", state.wife.money);
      }
    );

    return {
      ...toRefs(state),
      xusuiRef,
      scoreRef,
    };
  },

  // data(){
  //   return {
  //     age2:20
  //   }
  // },
  // computed:{
  //   xusui2(){
  //     return this.age2 + 1
  //   }
  // }
};
</script>
